﻿using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace OrderingFoot.Core
{
    /// <summary>
    /// 注册服务
    /// </summary>
    public static class RegisterServiceExtensions
    {
        /// <summary>
        /// 注册接口服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="assemblyName">AiQiuQuan.Sport.*.dll,支持通配符*；空不注入</param>
        /// <param name="pathList">程序集查找路径，默认查找程序根目录</param>
        /// <returns></returns>
        public static IServiceCollection RegisterInterfaceService(this IServiceCollection services, string assemblyName, IList<string> pathList = null)
        {
            if (string.IsNullOrWhiteSpace(assemblyName))
            {
                return services;
            }

            pathList ??= new List<string> { AppContext.BaseDirectory };

            foreach (var path in pathList)
            {
                try
                {
                    var allAssemblyList = Directory.GetFiles(AppContext.BaseDirectory, assemblyName);
                    foreach (var item in allAssemblyList)
                    {
                        var assembly = Assembly.LoadFrom(item);
                        var typeList = assembly.GetExportedTypes().Where(m => m.IsClass && !m.IsAbstract && !m.IsInterface && !m.IsGenericType).ToList();
                        foreach (var type in typeList)
                        {
                            if (typeof(ITransientDependency).IsAssignableFrom(type))
                            {
                                var interfaceList = type.GetInterfaces().Where(m => m.Name != typeof(ITransientDependency).Name).ToList();
                                interfaceList.ForEach(m => { services.AddTransient(m, type); });
                            }
                            else if (typeof(IScopedDependency).IsAssignableFrom(type))
                            {
                                var interfaceList = type.GetInterfaces().Where(m => m.Name != typeof(IScopedDependency).Name).ToList();
                                interfaceList.ForEach(m => { services.AddScoped(m, type); });
                            }
                            else if (typeof(ISingletonDependency).IsAssignableFrom(type))
                            {
                                var interfaceList = type.GetInterfaces().Where(m => m.Name != typeof(ISingletonDependency).Name).ToList();
                                interfaceList.ForEach(m => { services.AddSingleton(m, type); });
                            }
                        }
                    }
                }
                catch
                {

                }
            }

            return services;
        }
    }
}
